<template>
  <div class="fillcontain">
    <head-top></head-top>
    <div class="table_container">
        <el-row :gutter="20">
            <el-col :span="10" :offset="3" >
           <el-input placeholder="请输入内容" v-model="input3" class="input-with-select">
                <el-select style="width:130px" v-model="select" slot="prepend" placeholder="请选择">
                    <el-option v-for="item in selectOptions"
                    :key="item.value" 
                    :label="item.lable"
                     :value="item.value"></el-option>
                </el-select>
                <el-button @click="getList()" slot="append" icon="el-icon-search" >搜索</el-button>
            </el-input>
          </el-col>
        </el-row>
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="props">
            <!-- 具体内容，下拉框 row是下拉框中的对象，包含每个属性的对象id，address-->
            <el-form label-position="left" inline class="demo-table-expand">
              <el-form-item label="景点 ID">
                <span>{{ props.row.id }}</span>
              </el-form-item>
              <el-form-item label="景点名称">
                <span>{{ props.row.name }}</span>
              </el-form-item>
              <el-form-item label="景点地址">
                <span>{{ props.row.addr.addr }}</span>
              </el-form-item>
              <el-form-item label="景点介绍">
                <span>{{ props.row.introduction }}</span>
              </el-form-item>

              <el-form-item label="景点通知">
                <span>{{ props.row.annocement }}</span>
              </el-form-item>

              <el-form-item label="人流量">
                <span>{{ props.row.population }}</span>
              </el-form-item>

              <el-form-item label="票名称">
                <span>{{ props.row.ticketDes }}</span>
              </el-form-item>

              <el-form-item label="票价">
                <span>{{ props.row.ticketPrice }}</span>
              </el-form-item>
              <el-form-item label="景点图片">
                <el-row type="flex" :gutter="20">    
                          <el-col  v-for="item in props.row.pics" :key="item.id" >             
                            <img
                            style="height: 100px;"
                            :src="item.url"
                            fit="fit"></img>  
                 </el-col> 
                 </el-row>
              </el-form-item>
            
            </el-form>
          </template>
        </el-table-column>
        <!-- table head -->
        <el-table-column label="景点名称" prop="name"> </el-table-column>
        <el-table-column label="景点地址" prop="addr.addr" > </el-table-column>
        <el-table-column label="人流量" prop="population" > </el-table-column>
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="mini" @click="handleEdit(scope.$index, scope.row)"
              >编辑</el-button
            >
            <el-button
              size="mini"
              type="primary"
              @click="addSceneryPics(scope.$index, scope.row)"
              >图片管理</el-button
            >
            <el-button
              size="mini"
              type="danger"
              @click="handleDelete(scope.$index, scope.row)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <div class="Pagination">
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-size="20"
          layout="total, prev, pager, next"
          :total="count"
        >
        </el-pagination>
      </div>
      <!-- 修改提示框 -->
      <el-dialog title="修改景点信息" v-model="dialogFormVisible">
        <div slot="footer">
          <el-form :model="selectTable">
            <el-form-item label="景点名称" label-width="100px">
              <el-input
                v-model="selectTable.name"
                auto-complete="off"
              ></el-input>
            </el-form-item>
            <div
              id="map-container"
              v-show="dialogFormVisible"
              style="width: 100%; height: 500px"
            ></div>
             <el-autocomplete
              style="width: 100%"
              popper-class="autoAddressClass"
              v-model="addr.addr"
              :fetch-suggestions="querySearchAsync"
              :trigger-on-focus="false"
              placeholder="详细地址"
              @select="handleSelect"
              
            >
     
            </el-autocomplete>
            <el-form-item label="景点介绍" label-width="100px">
              <el-input v-model="selectTable.introduction"></el-input>
            </el-form-item>
            <el-form-item label="景点通知" label-width="100px">
              <el-input v-model="selectTable.annocement"></el-input>
            </el-form-item>
            <el-form-item label="票名称" label-width="100px">
              <el-input v-model="selectTable.ticketDes"></el-input>
            </el-form-item>
            <el-form-item label="票价" label-width="100px">
              <el-input v-model="selectTable.ticketPrice"></el-input>
            </el-form-item>
          </el-form>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="updateShop">确 定</el-button>
        </div>
      </el-dialog>

      <!-- 上传图片 -->
      <el-dialog title="查看图片" v-model="dialogUploadPicVisible">
        <div slot="footer" style="min-height:500px">
             <div class="container wrapper">
                
                    <div
                      v-for="(item,index) in selectTable.pics" :key="item.id" >             
                            <img ref="img"
                            style="height:100px "
                            :src="item.url"
                            fit="fit"></img> 
                             <div ref="imgDelete" class="delete-img">
                         <i class="el-icon-delete text-red" @click="deleteImg(item.id,index)"></i>
                       </div>  
                      </div>                        
                </div>

        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogUploadPicVisible = false">确定</el-button>
              <!-- <el-row type="flex" >     -->
                    <!-- <el-col :span="3">   -->
                             <el-upload class="avatar-uploader" 
                             action="http://localhost:8090/tourism/scenery/addSceneryPic" 
                                :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload"
                                 :data="{scenId:selectTable.id}"
                                :show-file-list="false"
                            >           
                           <el-button type="primary" >添加图片</el-button>
                             </el-upload>
    
                    <!-- </el-col>  -->
                <!-- </el-row> -->
        </div>
      </el-dialog>

    </div>
  </div>
</template>

<script>

import headTop from "../components/headTop";
import { baseUrl, baseImgPath } from "@/config/env";
import { getScenerys, updateSceneryById,importFile,deleteSceneryById ,getScenerysByPage,delteSceneryPicById} from "@/api/scenery";
import loadBMap from "@/api/baiduMap";
import { getAddressById } from '@/api/getData';

export default {
  data() {
    return {
      baseUrl,
      baseImgPath,
      city: {},
      offset: 0,
      limit: 20,
      count: 0,
      tableData: [],
      currentPage: 1,
      selectTable: {},
      dialogFormVisible: false,
      categoryOptions: [],
      selectedCategory: [],
      addr: {},//记录当前位置
      scenerys: [],
      map: "", //地图实例
      mk: "", //Marker实例
      dialogUploadPicVisible: false,
      sceneryPic:{},
      selectedSceneryId:-1,
      fileList:[],
       input3: "",
      select: 1,
      selectOptions: [
        {
          lable: "景点名称",
          value: "1",
        },
         {
          lable: "景点位置",
          value: "2",
        },
      ]
    };
  },
  created() {
    this.select = this.selectOptions[0].value;
    this.initData();
    console.log(11111);
  },
  components: {
    headTop,
  },
  //这里运用async/await 进行异步处理，保证BMap加载进来后才执行后面的操作
  async mounted() {
    await loadBMap("F0QZjfxl5SM6vG3XwdoM5UVVjGWwPM0K"); //加载引入BMap
  },


  methods: {

     handleAvatarSuccess(res, file) {
      if(res.code>=0){
        let pics = this.selectTable.pics
        this.selectTable.pics = pics.concat(res.data)       
        this.$message({
          message: '添加成功',
          type:"success"
        });
      }else{
         this.$message({
          message: res.message,
          type:"fail"
        });
      }
        
        console.log(res);
      },
      beforeAvatarUpload(file) {
        
        const isJPG = file.type === 'image/jpeg'||file.type=='image/jpg'||file.type=='png';
        const isLt2M = file.size / 1024 / 1024 < 1;
 
        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG ,PNG,JPEG格式!');
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 1MB!');
        }
        return isJPG && isLt2M;
      },

       // 删除图片
    async deleteImg(id,index) {
      this.$confirm("是否删除该照片?", "删除", {
         distinguishCancelAndClose: true,
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async() => {
          console.log("picture Id",id);
          if(id){
           await  delteSceneryPicById(id)
            this.$message({
            type: "success",
            message: "删除成功!"
          });
          this.selectTable.pics.splice(index,1)
          }
         
        })
        .catch((action) => {
          if (action === 'cancel'){
            this.$message({
              type: "info",
              message: "已取消删除"
            });
          }
        });
    },
    //初始化数据
    async initData() {
      try {
  
        this.getList();
        // const countData = await getResturantsCount();

        // this.getResturants();
      } catch (err) {
        console.log("获取数据失败", err);
      }
    },

    //地址，经纬度,
 //地址，经纬度
    initmyMap(lat=28.689454978197837,lng=115.86458548977238) { 
      console.log("initMap lat",lat,"lng",lng);
   
//新建地图实例，enableMapClick:false ：禁用地图默认点击弹框
      this.map = new BMap.Map("map-container", { enableMapClick: false }); 
      var point = new BMap.Point(Number(lng).toFixed(5),Number(lat).toFixed(5));
      this.map.centerAndZoom(point, 19);
      console.log('initPoint');
      this.map.enableScrollWheelZoom(true); //启用滚轮放大缩小，默认禁用
       this.mk = new BMap.Marker(point,{enableDragging:true})
      this.map.addOverlay(this.mk)
    let that = this;
     this.mk.addEventListener('dragend', function(e){
    
        that.getAddrByPoint(e.point) //拖拽结束后调用逆地址解析函数，e.point为拖拽后的地理坐标
    })
    
    },

    async getList() {
      let info = this.input3;
      let type = this.select
      let currentPage = this.currentPage;
      let pageSize = this.limit;
      let res;
      res = await getScenerysByPage(currentPage,pageSize,{info,type})

      if (res && res.code >= 0) {
        this.tableData = res.data.rows;
        this.count = res.data.totalCount;
      
      } else {
        console.log(res.message);
      }
    },
    //添加地图控件
    addMapContro(){
        var navigationControl = new BMap.NavigationControl({
        //创建一个特定样式的地图平移缩放控件
        anchor: BMAP_ANCHOR_TOP_RIGHT, //靠右上角位置
        type: BMAP_NAVIGATION_CONTROL_SMALL, //SMALL控件类型
      });
      this.map.addControl(navigationControl); //将控件添加到地图
      var geolocationControl = new BMap.GeolocationControl({
        anchor: BMAP_ANCHOR_BOTTOM_LEFT,
      }); //创建一个地图定位控件
      geolocationControl.addEventListener("locationSuccess", function (e) {
        //绑定定位成功后事件
        that.getAddrByPoint(e.point); //定位成功后调用逆地址解析函数
      });
      geolocationControl.addEventListener("locationError", function (e) {
        //绑定定位失败后事件
        alert(e.message);
      });
      this.map.addControl(geolocationControl); //将控件添加到地图
    },
    /**
 * 逆地址解析函数（根据坐标点获取详细地址）
 * @param {Object} point   百度地图坐标点，必传
 */
  getAddrByPoint(point){
  var that = this;
  var geco = new BMap.Geocoder();
  geco.getLocation(point, function(res){
  	console.log(res)  //内容见下图
    that.mk.setPosition(point) //重新设置标注的地理坐标
    that.map.panTo(point)  //将地图的中心点更改为给定的点
    console.log("getAddrBypoint res",res);
     const latitude = res.point.lat
      const longitude = res.point.lng
      const {province,city} = res.addressComponents
      that.addr = {latitude,longitude,province,city,addr:res.address}
  })
},



    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      this.offset = (val - 1) * this.limit;
      this.getList();
    },
    async handleEdit(index, row) {
      this.addr = row.addr
      //index 就是第几个，可以从scenery直接取
      // console.log("handleEdit(index, row)", index, row);
      const{latitude,longitude} =this.addr

      this.initmyMap(latitude,longitude);
      this.selectTable = row;

      this.dialogFormVisible = true;
    },
    addSceneryPics(index, row) {
        this.selectTable=row
        this.dialogUploadPicVisible=true
    

    },
    addScenery(index, row) {
      this.$router.push({
        path: "addScenery",
        query: { restaurant_id: row.id },
      });
    },
    async handleDelete(index, row) {
      try {
       
            const res = await deleteSceneryById(row.id);
            if (res.code >= 0) {
            this.$message({
                type: "success",
                message: "删除景点成功",
            });
            this.tableData.splice(index, 1);
            this.count--;
            } else {
            throw new Error(res.message);
            }
      } catch (err) {
        this.$message({
          type: "error",
          message: err.message,
        });
        console.log("删除店铺失败");
      }
    },
    //执行搜索操作，queryString是搜索的内容，cb中传入到搜寻显示框的内容，必须是个数组
    querySearchAsync(str,cb){
      var options = {
        onSearchComplete: function(res){ //检索完成后的回调函数
          var s = [];
          console.log("local",local);
          if (local.getStatus() == BMAP_STATUS_SUCCESS){
            console.log('isok',res);
            for (var i = 0; i < res.getCurrentNumPois(); i ++){
              console.log('res.getpoi',res.getPoi(i));
              let r = res.getPoi(i);
              //这里必须设置value
              r.value = r.province+r.address+r.title
              s.push(r);
            }
            console.log("querySearchAsync s",s);
            cb(s) //获取到数据时，通过回调函数cb返回到<el-autocomplete>组件中进行显示
          } else{
            console.log("querySearchAsync else");
            cb(s)
          }
        }
      }
      var local = new BMap.LocalSearch(this.map, options) //创建LocalSearch构造函数
      local.search(str) //调用search方法，根据检索词str发起检索
    },
    handleSelect(item) {
      //选中必须记录信息
      console.log("item select",item);
      const latitude = item.point.lat
      const longitude = item.point.lng
   
      const {province,city,title,address}=item
      if(this.addr.id){
        const id= this.addr.id
         let addr= province+address+title
        this.addr = {id,province,city,latitude,longitude,addr}
      }else{
        console.log("erro");return ;
      }
     
     
      // this.selectTable.address = item.address + item.title; //记录详细地址，含建筑物名
      // this.addrPoint = item.point; //记录当前选中地址坐标
      // this.getAddrByPoint(item.point)
      // console.log("select point ",item.point);
      this.map.clearOverlays() //清除地图上所有覆盖物
      this.mk = new BMap.Marker(item.point) //根据所选坐标重新创建Marker
      this.map.addOverlay(this.mk) //将覆盖物重新添加到地图中
      this.map.panTo(item.point) //将地图的中心点更改为选定坐标点
    },



    //更新景点
    async updateShop() {
      try {
        //把address添加到selectable中
        // Object.assign(this.selectTable, this.addr);

        console.log("this.selectTable", this.selectTable);
        if(this.addr.id){
          this.selectTable.addr = this.addr
        }
        const res = await updateSceneryById(this.selectTable);
        if (res.code >= 0) {
          this.$message({
            type: "success",
            message: "更新景点信息成功",
          });

          this.getList();
        } else {
          this.$message({
            type: "error",
            message: res.message,
          });
        }
      } catch (err) {
        console.log("更新景点信息失败", err);
      }
      this.dialogFormVisible = false;
    },
  },
};
</script>

<style lang="less">
@import "../style/mixin";
.demo-table-expand {
  font-size: 0;
}
.demo-table-expand label {
  width: 90px;
  color: #99a9bf;
}
.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}
.wrapper{
   display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  // grid-gap: 5px;
  // grid-auto-rows: 100px;
}
.table_container {
  padding: 20px;
}
.Pagination {
  display: flex;
  justify-content: flex-start;
  margin-top: 8px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #20a0ff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  line-height: 120px;
  text-align: center;
}
.avatar {
  width: 120px;
  height: 120px;
  display: block;
}
</style>
